<template>
  <div class="container">
    <div class="ip_white_list">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="search">
          <a-form-item label="创建时间">
            <a-range-picker
              v-model="queryParam.time"
              :ranges="{
              '1周': [moment().startOf('day').subtract(1, 'weeks'), moment()],
              半个月: [moment().startOf('day').subtract(14, 'days'), moment()],
              '3个月': [moment().startOf('day').subtract(3, 'months'), moment()],
              '6个月': [moment().startOf('day').subtract(6, 'months'), moment()],
              '1年': [moment().startOf('day').subtract(1, 'years'), moment()],
            }"
              format="YYYY-MM-DD"
              @change="onChangeData"
              :disabled-date="disabled"
            />
          </a-form-item>
          <a-form-item label="管理员ID">
            <a-input v-model="queryParam.queryUserId" placeholder="管理员ID" />
          </a-form-item>
          <a-form-item label="IP地址">
            <a-input v-model="queryParam.ipAddress" placeholder="IP地址" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" htmlType="submit" @click="search">查询</a-button>
            <a-button htmlType="submit" class="ml15" @click="searchReset">重置</a-button>
            <a-button htmlType="submit" type="primary" class="ml15" @click="addAndEdit('add')">+新增</a-button>
          </a-form-item>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        :columns="columns"
        :data="loadData"
        bordered
        :rowKey="(record) => record.id"
      >
        <template slot="action" slot-scope="text, record">
          <a-button size="small" type="primary" @click="addAndEdit('edit', record)">编辑</a-button>
          <a-button size="small" type="danger" class="ml15" @click="deleteModal(record)">删除</a-button>
        </template>
      </s-table>
      <a-modal :title="title" v-model="visible" @ok="handleOk" :maskClosable="false">
        <a-form :form="form" class="permission-form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="IP地址">
            <a-input
              v-decorator="[
              'ipAddress',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入IP地址!',
                  },
                ],
                initialValue: title === '新增' ? '' : info.ipAddress,
              },
            ]"
              placeholder="请输入IP地址"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="描述">
            <a-textarea
              v-decorator="[
              'remark',
              {
                initialValue: title === '新增' ? '' : info.remark,
              },
            ]"
              placeholder="请输入描述内容"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              :maxLength="100"
            />
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal title="提示信息" v-model="visible1" @ok="deleteList">
        <p>确定要删除信息？</p>
        <p>注：IP信息删除，不可回复</p>
      </a-modal>
    </div>
  </div>
</template>

<script>
import STable from '@/components/Table'
import { IpList, saveIpList, updateIpList, deleteIpList, detailsIpList } from '@/api/back-office-management'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  name: 'ipWhitelisting',
  components: {
    STable,
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  data() {
    return {
      form: this.$form.createForm(this),
      formLayout: 'horizontal',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      visible: false,
      visible1: false,
      title: '',
      info: {},
      columns: [
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center'
        },
        {
          title: 'IP地址',
          dataIndex: 'ipAddress',
          align: 'center'
        },
        {
          title: '描述',
          dataIndex: 'remark',
          customRender: (text) => (text ? text : '-'),
          align: 'center'
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          align: 'center'
        },
        {
          title: '创建人',
          dataIndex: 'createUser',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          slots: { title: 'action' },
          scopedSlots: { customRender: 'action' },
          align: 'center'
        },
      ],
      // 查询条件参数
      queryParam: { time: [null, null], queryUserId: '', ipAddress: '' },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const { userId } = this.userInfo

        let params = {
          ...parameter,
          userId,
          ...this.queryParam,
          startTime: this.queryParam.time[0] ? `${this.queryParam.time[0]} 00:00:00` : '',
          endTime: this.queryParam.time[1] ? `${this.queryParam.time[1]} 23:59:59` : '',
        }
        delete params.time
        return new Promise((resolve, reject) => {
          IpList(params)
            .then((res) => {
              if (res.code === 200) {
                resolve(res.data)
              } else {
                this.$message.error(res?.msg)
              }
            })
            .catch((err) => {
              reject(err)
            })
            .finally(() => {})
        })
      },
      accountStateType: ['启用', '禁用', '冻结'],
    }
  },
  methods: {
    moment,
    onChangeData(dates, dateStrings) {
      this.queryParam.time = dateStrings
    },
    disabled(current) {
      return current && current > moment().subtract().endOf('day')
    },
    addAndEdit(type, record = {}) {
      this.form.resetFields()
      if (type === 'edit') {
        const { userId } = this.userInfo
        const params = {
          id: record.id,
          userId,
        }
        detailsIpList(params).then((res) => {
          if (res.code === 200) {
            this.info = res.data ?? {}
          }
        })
      } else {
        this.info = {}
      }
      this.title = type === 'edit' ? '编辑' : '新增'
      this.visible = true
    },
    refresh(isBackToFirstPage = false) {
      this.$refs.table.refresh(isBackToFirstPage)
    },
    search() {
      this.refresh(false)
    },
    searchReset() {
      this.queryParam = { time: [null, null], queryUserId: '', ipAddress: '' }
      this.refresh(true)
    },

    deleteModal(row) {
      this.visible1 = true
      this.info = row
    },

    deleteList() {
      const { userId } = this.userInfo
      const params = {
        id: this.info.id,
        userId,
      }
      deleteIpList(params).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.visible1 = false
          this.$refs.table.refresh()
          this.info = {}
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const { userId } = this.userInfo
          let params = {
            id: this.info.id ?? '',
            ...values,
            userId,
          }
          if (this.title === '新增') {
            delete params.id
          }
          let url = this.title === '新增' ? saveIpList : updateIpList
          url(params).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.visible = false
              this.info = {}
              this.$refs.table.refresh()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
.ip_white_list {
  .delete {
    color: #e94141;
    margin-left: 15px;
  }
  .form {
    display: flex;
    margin-bottom: 20px;
    flex-wrap: wrap;
  }
  .red {
    color: #e94141;
  }
  .green {
    color: #46c16a;
  }
  .permission-form {
    :deep(.permission-group) {
      margin-top: 0;
      margin-bottom: 0;
    }
  }
}
.modal {
  /deep/ .ant-modal {
    width: 1000px !important;
  }
  .user_harder_img {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    span {
      padding-left: 15px;
    }
    img {
      width: 30px;
      height: 30px;
      border-radius: 50%;
    }
  }
  .user_info {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    border-bottom: 1px solid #f3f4f6;
    &:last-child {
      border-bottom: none;
    }
    .item {
      display: flex;
      div {
        height: 40px;
        width: 50%;
      }
      span {
        &:first-child {
          width: 100px;
          text-align: left;
          padding: 0 15px;
        }
        &:last-child {
          text-align: left;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      .textarea {
        width: 80%;
      }
    }
  }
}
</style>
